package com.demo.json;

import com.demo.database.jdbc.DBUtil;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.stream.Collectors;

@WebServlet("/json")
public class JsonServlet extends HttpServlet {

    @Override
    // curl -v http://localhost:8080/homework01/json
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //创建一个简单的Student对象
        StudentDTO studentDTO = new StudentDTO("201641412101", "郑斯钧", "网络空间安全学院", "软件工程", "16软件2班");

        //获取对象的JSON，需要使用JsonbBuilder.toJson()方法
        Jsonb jsonb = JsonbBuilder.create();
        String jsonStudent = jsonb.toJson(studentDTO);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        response.getWriter().println(jsonStudent);
    }

    @Override
    // curl -v -H "Content-Type: application/json" http://localhost:8080/homework01/json -X POST --data '{"专业":"软件工程","姓名":"郑斯钧","学号":"201641412101","部门":"网络空间安全学院", "班级":"16软件2班"}'
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStudent;
        Jsonb jsonb = JsonbBuilder.create();
        String postJsonStr = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        System.out.println("编码后postJsonStr: " + postJsonStr);

        //利用Jsonb把Json字符串转换为对象
        StudentDTO studentDTO = jsonb.fromJson(postJsonStr, StudentDTO.class);
        System.out.println(studentDTO);

        //把获取的字符串原样返回为Json
        if (DBUtil.insertToStudent(studentDTO)) {
            //插入数据成功
            jsonStudent = "{\"code\":0,\"msg\":\"操作成功\"}";
        } else {
            //插入数据失败
            jsonStudent = "{\"code\":-1,\"msg\":\"操作失败\"}";
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        response.getWriter().println(jsonStudent);
    }
}
